package com.example.customviewpage;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/6/14.
 */

class MyAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {
    private final MainActivity context;
    private  ViewPager viewPager;
    private ArrayList<Integer> datas;
    private int currentPosition;

    public MyAdapter(MainActivity mainActivity, int[] ins, ViewPager viewPager) {
        this.context = mainActivity;
        datas = new ArrayList<>();
        for (int i = 0; i < ins.length; i++) {
            datas.add(ins[i]);
        }
        datas.add(0,ins[ins.length-1]);
        datas.add(datas.size(),ins[0]);
        this.viewPager = viewPager;
        viewPager.addOnPageChangeListener(this);

    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView view = new ImageView(context);

        view.setBackgroundResource(datas.get(position));
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);
        container.removeView((View) object);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//        Log.e("viewpager","onPageScrolled=="+"position==" +position+
//                ",,offset==" +positionOffset+
//                ",,pixels=="+positionOffsetPixels);
    }

    @Override
    public void onPageSelected(int position) {
//        Log.e("viewpager", "onPageSelected=="+"position=="+position);
        currentPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        Log.e("viewpager", "onPageScrollStateChanged=="+"state=="+state);
        if(state==1){
            //滑动过程中，如果position==0，则选中 sizi-1
            //如果position==sizi-1; 则选中0
            if(currentPosition==0){
                viewPager.setCurrentItem(datas.size()-2,false);
            }
            if(currentPosition==datas.size()-1){
                viewPager.setCurrentItem(1,false);
            }
        }
    }
}
